package 二维码.原生;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;

public class ErWerMa {
    private static final int WHITE = 0xFFFFFFFF;
    private static final int BLACK = 0xFF000000;

    public static void main(String[] args) throws IOException, WriterException {
        String url = "https://mp.csdn.net/mp_blog/manage/article?spm=1000.2115.3001.5448";
        int width = 400;
        int height = 400;
        Hashtable<EncodeHintType,String> hashtable = new Hashtable<>();
        hashtable.put(EncodeHintType.CHARACTER_SET,"UTF-8");
        //位矩阵
        BitMatrix bitMatrix = new MultiFormatWriter().encode(url, BarcodeFormat.QR_CODE,width,height,hashtable);
        File file = new File("C:\\Users\\mfg\\Desktop\\"+File.separator+"user.png");
        ErWerMa.intoFile(bitMatrix,"png",file);

    }

    //绘制图片
    public static BufferedImage buildImg(BitMatrix bitMatrix){   //bitMatrix  //位矩阵
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage img = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        for(int x = 0; x < width; x++){
            for(int y = 0; y < height; y++){
                img.setRGB(x,y,bitMatrix.get(x,y) ? BLACK : WHITE);
            }
        }
        return img;
    }

    // 写入文件
    public static void intoFile(BitMatrix bitMatrix, String format, File file) throws IOException {
        BufferedImage image = buildImg(bitMatrix);
        if(!ImageIO.write(image, format, file)){
            throw new IOException("格式不对");
        }
    }

    //写入文件流
    public static void writeFlow(BitMatrix bitMatrix, String fm, OutputStream os) throws IOException {
        BufferedImage bm = buildImg(bitMatrix);
        if(!ImageIO.write(bm,fm,os)){
            throw new IOException("格式不对");
        }
    }

}
